import datetime

import pytz
from minio import Minio
from minio.error import MinioException


class MinioClass():

    def login(self, login_info):
        # 使用endpoint、access key和secret key来初始化minioClient对象。
        self.minioClient = Minio(login_info['minio_url'],
                                 access_key=login_info['minio_access_key'],
                                 secret_key=login_info['minio_secret_key'],
                                 secure=False)

    def create_buckets(self, buckets_name, location='cn-north-1'):
        """
        创建桶
        location: 存储桶被创建的region(地区)，默认是us-east-1(美国东一区)
        """
        try:
            self.minioClient.make_bucket(buckets_name, location=location)
        except MinioException as err:
            print(err)

    def get_bucket_list(self):
        """
        列出所有桶
        """
        try:
            buckets_data = []
            buckets = self.minioClient.list_buckets()
            for bucket in buckets:
                bucket_data = {"bucket_name": bucket.name,
                               "bucket_creation_date": bucket.creation_date,
                               }
                buckets_data.append(bucket_data)
            return buckets_data
        except Exception as err:
            print(err)

    def get_list_objects(self, bucket_name, prefix="", recursive=False):
        """
        列出桶里面的对象
        @param bucket_name: 桶名称
        @param prefix: 路径
        @param recursive: True时，遍历路径下所有对象，包括目录里面的
        @return:
        """
        object_data = []
        objects = self.minioClient.list_objects(bucket_name, prefix=prefix, recursive=recursive)
        for obj in objects:
            # print(obj)
            object_data.append({
                "bucket_name": obj.bucket_name,
                "object_name": obj.object_name.encode('utf-8'),
                "last_modified": obj.last_modified,
                "etag": obj.etag,
                "is_dir": obj.is_dir,
                "size": obj.size,
                "content_type": obj.content_type,
            })
        return object_data

    def file_put_object(self, bucket_name, object_name, local_file_path, content_type='application/octet-stream'):
        """
        上传文件到对象
        @param bucket_name: 桶名
        @param object_name: 上传后的对象名
        @param local_file_path: 本地文件名
        @param content_type: 对象类型，默认
        @return:
        """
        try:
            push_obj = self.minioClient.fput_object(bucket_name, object_name,
                                               local_file_path,
                                               content_type=content_type)
        except MinioException as err:
            print(err)

        return True

    def remove_object(self, bucket_name, object_name_list):
        try:
            for object_name_list_one in object_name_list:
                # 删除指定路径下的所有对象
                objects_to_remove = []
                objects_in_directory = self.minioClient.list_objects(bucket_name, prefix=object_name_list_one,
                                                                     recursive=True)
                for obj in objects_in_directory:
                    objects_to_remove.append(obj.object_name)

                if len(objects_to_remove) > 0:
                    # 执行删除操作
                    for obj in objects_to_remove:
                        self.minioClient.remove_object(bucket_name, obj)
                    print('路径删除成功')
                else:
                    print('路径为空或不存在')

                directory_path = object_name_list_one.rstrip('/') + '/'
                self.minioClient.remove_object(bucket_name, directory_path)
        except MinioException as err:
            print(err)

        return True

    def file_data_extent(self, object_list, start_time, end_time):
        """
        过滤对象中数据基于修改时间区间的对象
        @param object_list: 对象列表
        @param start_time: 开始时间 格式：'%Y-%m-%d %H:%i:%S
        @param end_time: 最后时间 格式：'%Y-%m-%d %H:%i:%S
        @return:
        """
        filter_data = []
        start_time = datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.timezone('UTC'))
        end_time = datetime.datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.timezone('UTC'))

        for object_list_one in object_list:
            if object_list_one['last_modified'] > start_time and object_list_one['last_modified'] < end_time:
                filter_data.append(object_list_one)

        return filter_data

    def file_get_object(self, bucket_name, object_name, local_file_path):
        """
        下载文件到本地
        @param bucket_name: 桶
        @param object_name: 对象
        @param local_file_path: 本地路径
        @return:
        """
        try:
            print(self.minioClient.fget_object(bucket_name, object_name, local_file_path))
        except MinioException as err:
            print(err)


minioc = MinioClass()
login_info={
    "minio_access_key": "minio",
    "minio_secret_key": "xxx",
    "minio_url": "10.233.50.119:9000"
}
minioc.login(login_info)
# obj_list = minioc.get_list_objects("sinopec-source-module",prefix="spread/")
# for obj_list_one in obj_list:
#     print(obj_list_one)


# dict_info = {
#     'minio_url': '10.11.6.80:9000',
#     'minio_access_key': 'minio',
#     'minio_secret_key': 'xxx',
# }
# minio_class = MinioClass()
# minio_class.login(dict_info)
# # test=minio_class.get_list_objects("spectrum-analysis-system", 'data/0000/20220506')
# dir_files=minio_class.get_list_objects("spectrum-analysis-system", 'data/0000/武汉市华中国际产业园/TODAY915')

# dict_info_2 = {
#     'minio_url': '10.102.63.41:9000',
#     'minio_access_key': 'minio',
#     'minio_secret_key': 'xxx',
# }
# minio_class_2 = MinioClass()
# minio_class_2.login(dict_info_2)
# # test=minio_class.get_list_objects("spectrum-analysis-system", 'data/0000/20220506')
# dir_files_2=minio_class_2.get_list_objects("spectrum-analysis-system", 'data/0000/四川自贡/ISQ-7000/')
#
# end_data_swap=[]


# try:
#     for dir_files_one in dir_files:
#         if dir_files_one['is_dir']:
#             dir_obj=minio_class.get_list_objects("spectrum-analysis-system", prefix=dir_files_one['object_name'], recursive=True)
#             for dir_obj_one in dir_obj:
#                 end_data_swap.append(dir_obj_one)
#         else:
#                 end_data_swap.append(dir_files_one)
# except:
#     pass


# start_time = datetime.datetime.strptime('2022-09-21', '%Y-%m-%d')
# end_time = datetime.datetime.strptime('2023-02-28 23', '%Y-%m-%d %H')
# try:
#     for dir_files_one in dir_files:
#         if dir_files_one['is_dir']:
#
#             dir_files_one_object_name = bytes.decode(dir_files_one['object_name'])
#
#             file_name = dir_files_one_object_name.split('/')[-2:]
#             file_name_time = file_name[0].split('.')[:1]
#             file_name_time_datetime = datetime.datetime.strptime(file_name_time[0], '%Y%m%d%H')
#
#             if file_name_time_datetime > start_time and file_name_time_datetime < end_time:
#                 dir_obj=minio_class.get_list_objects("spectrum-analysis-system", prefix=dir_files_one['object_name'], recursive=True)
#                 for dir_obj_one in dir_obj:
#                     end_data_swap.append(dir_obj_one)
#         else:
#             dir_files_one_object_name = bytes.decode(dir_files_one['object_name'])
#
#             file_name = dir_files_one_object_name.split('/')[-1:]
#             file_name_time = file_name[0].split('.')[:1]
#             try:
#                 file_name_time_datetime = datetime.datetime.strptime(file_name_time[0], '%Y%m%d%H')
#             except:
#                 file_name_time_datetime = datetime.datetime.strptime(file_name_time[0], '%Y%m%d%H%M')
#             if file_name_time_datetime > start_time and file_name_time_datetime < end_time:
#                 end_data_swap.append(dir_files_one)
# except:
#     pass

# print(end_data_swap)
# h=open("all.txt", "w")
# h.write(str(end_data_swap))
# h.close()

# minio_class.create_buckets("wangwuli")

# minio_class.file_put_object("wangwuli", "__init4444__.py", "./__init__.py")

# test=minio_class.get_list_objects("wangwuli", '/')
# for test_one in test:
#   print (test_one)



# h=open("all.txt", "r")
# all_str = h.read()
# h.close()
# all_list=eval(all_str)
# try:
#     for all_one in all_list:
#         object_name_str = bytes.decode(all_one['object_name'])
#         object_name_str_ = object_name_str.replace("data/0000/武汉市华中国际产业园/TODAY915", "data/0000/四川自贡/ISQ-7000")
#
#         get_obj = minio_class.file_get_object('spectrum-analysis-system', all_one['object_name'], object_name_str)
#
#         minio_class_2.file_put_object("spectrum-analysis-system", object_name_str_, object_name_str)
# except:
#     pass
#
# print(all_list)


job_list = ["spread/ffde2360a0ab430e8d3bb6e4f885d02a","spread/f81c1ac57e0442f5bb4c2afef68e0d4e","spread/f5134cde5e36469298b602c764b95575","spread/f1d40baa0f494424b6af3996686dc16e","spread/f0c9e908458e4e43a4fbcc8a0789e51f","spread/e96dab73f1cf41f099b9c7890d7a20bd","spread/e94d9341be0a498c997517dddbed4267","spread/e793d2c33fa2458f9d7a8ccf12213345","spread/e3f2341fb9994cbbbe05516eab8419d5","spread/df4ecfb8f3a84c068e79aca58a9e847e","spread/d2ed90f9b2f64a1c824d270ce04f5aa3","spread/c68100047ad84167bbc910c89c614214","spread/c10d6c2187dc4537b79f2cdcff306ce0","spread/bcc355f9a62e4c8b887f71a970738140","spread/b991bac6c1064b4ba43df93f1b274358","spread/b8bf7f2c96a44e6dacd8acc97a0579f3","spread/b7302f0501694f45961cba5a25883aa7","spread/b46d8943f85840ec996540544c71bac9","spread/b4124aa57dcb400abb1bf31e299ae46e","spread/af612c561ed34152b1a021b6e092a3cc","spread/ad30297ae8fb4fe2bec919d37fdcd2d7","spread/aa50cb89a0eb4b719905cc417040d9ca","spread/a479d80937274d418d2d626d28fc9610","spread/a12fe297f95e4816b85b4c675d6a5ba4","spread/60319609b5c7465393a2a27349157aec","spread/4228558b3b5340dc872dd52e4127982a","spread/645765de20f34a72ae9b61e479217b59","spread/94279d1a49b045d182515acbd8526ceb","spread/56431b723bca40a185d60bab89ef3ec6","spread/19784a00913a45f58726708bd4012786","spread/9526a009348d41889c75334d60bd242d","spread/8066c446493c4e779dd0718dd445f111","spread/950a2d15cbc34e2fa58b008c88ab9fc9","spread/782e2b52a66249759629b361f1691eb3","spread/770db08d53a74856bc48d06c9daba758","spread/469feb3d0a754fe59632d38bd89b7dec","spread/466eaf3b992145b29c51410177d18a63","spread/428df856d65940919609c78c405ece13","spread/412dd1cfbf484f40b7237ebcb787d9ad","spread/403bd31192f9466daf26909932bf0519","spread/367d0c975280465890f0d5f439832b92","spread/339ea6a2b9434c2fa6267c1ee47df31c","spread/0234d94b7e4b47ecb72cc6f1f10bc17d","spread/222a3ea66f0e4d7faf838e6bcaa816ad","spread/173cc434daa04aa48fa3de98d7226626","spread/112fd22e46b8460e904237153d056cbf","spread/93f95cc514124fb892e46cf7ca061d18","spread/87dae7d3d5bc4bf9bd767835a3b0bfef","spread/070e20c8e0a04e158907dbe044c70596","spread/69e3096ed55a4bf6a5c7c338cfc38647","spread/46ee0aa987fd49479775c92feaf3ba4f","spread/26f48c9c1de84117901d323e3f4b045b","spread/26f445f141954c5188512b8eb9dfaf6c","spread/17d7317db015426eac01aedbc614934e","spread/16f149c29cfd454a8592d1ad2c02b09e","spread/16b7ae2e35504e34a2fc172ecef0e1f6","spread/14f8c67aeeb64c8d85b4eaaea4d580f7","spread/9fbe0ffb60bc40c29ca0374f193ee81b","spread/9c5228351f48464fb056cb1cc2b2cd5c","spread/9b59bb083ed34ccb84281f3e99f6b54f","spread/9b04b5f89114432eaccf3ca899fa661f","spread/8f05268708c44590b7f060f452009dbc","spread/8e97f30094724a8ab50cf78e018cdc96","spread/7da061ac54cb4924bd2c9f3969072526","spread/7d2728b2525f484092bd715e2e4dab6c","spread/5f56ef49f16243999acc6cefb7324268","spread/5f1a344135604bfb8abab6b39c7d15f7","spread/5d65bf58a3524650b651b8d4e3e9f9db","spread/5af80f798d7341bf847d99dd85bbd364","spread/4f5f59528ead46a7a4f777acda86d61c","spread/4abcf34e9ab64299a37b142aa09c9837","spread/3da9c6488283400493a4032cd2def684","spread/3d73f41f3c1c4f689c6ccf4a97967dab","spread/3b4b536509764170869fd2a6468ca122","spread/2fc1e07a9e634475b494613a738410a1","spread/2f37ffb5b07c4482acd33bcb342699af","spread/2e90b3c7bf744158a0c9a5f9779b3b4e","spread/2c5697241a05407baea421bfd3655907","spread/2a2bc8fd51204621a5b81c2f2120961a","spread/1eceab553f53458d8a6b22adc9b93f58","spread/1c661222cdce4ec4a3456e02fa3b9377","spread/0de6e141ecbb48b78803b2fff11614ed","spread/0d3e5b5bc3f04676b40a8e94f723f99e"]
minioc.remove_object("sinopec-source-module", job_list)